﻿using System;
using CoreEx.Common.Validation;
using CoreEx.DynamicInvoker;
using LinFu.AOP.Interfaces;
using LinFu.IoC.Configuration;
using LinFu.IoC.Interfaces;

namespace CoreEx.Common.Tests
{
    [Implements(typeof(IInterceptor),LifecycleType.OncePerRequest, ServiceName = "DataErrorInfoInterceptor")]
    public class SampleDataErrorInfoInterceptor : IInterceptor, IInitialize
    {
        private IServiceContainer _serviceContainer;

        private object _actualTarget;

        private Type _targetType;

        public SampleDataErrorInfoInterceptor(object actualTarget, Type targetType)
        {
            _actualTarget = actualTarget;
            _targetType = targetType;
        }

        public object Intercept(IInvocationInfo info)
        {
            if (info.TargetMethod.Name == "get_Item")
            {                                
                var propertyValidatorType = typeof (IPropertyValidator<>).MakeGenericType(_targetType);
                var propertyValidator = _serviceContainer.GetService(propertyValidatorType);
                var result = propertyValidatorType.DynamicInvoke(propertyValidator,"Validate", new[] {_actualTarget, info.Arguments[0]});
                return result;
            }
            return info.TargetMethod.DynamicInvoke(_actualTarget, info.Arguments);
        }

        public void Initialize(IServiceContainer source)
        {
            _serviceContainer = source;
        }
    }
}
